# -*- coding: utf-8 -*-
import json
import requests
import sys


class DingApi(object):
    def __init__(self, appkey, appsecret):
        """
        :param corp_id:  钉钉应用的唯一标识key
        :param corp_secret: 钉钉应用的密钥。AppKey和AppSecret可在钉钉开发者后台的应用详情页面获取。
        """
        self.appkey = appkey
        self.appsecret = appsecret
        self.token = self.access_token()
        self.dept_dict = self.gen_dept_dict()

    def access_token(self):
        """
        获取企业内部应用的access_token，参考官方文档：https://open.dingtalk.com/document/orgapp-server/obtain-orgapp-token
        :return: access_token
        """
        url = 'https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s' % (self.appkey, self.appsecret)
        ret = json.loads(requests.get(url=url).text)
        if ret['errcode'] != 0:
            print(ret)
        return ret['access_token']

    def get_all_dept(self):
        """
        获取企业的所有部门的列表
        :return: 返回一个包含所有部门的列表
        """
        url = 'https://oapi.dingtalk.com/department/list?access_token=%s' % self.token
        ret = json.loads(requests.get(url=url).text)
        if ret["errcode"] != 0:
            print(ret)
        return ret


    def get_dept_user(self, dept_id):
        """
        :param department_id: 部门ID int
        :return: 部门的用户列表 list
        """
        url = 'https://oapi.dingtalk.com/user/list?access_token=%s&department_id=%s' % (self.token, dept_id)
        # url = 'https://oapi.dingtalk.com/topapi/v2/user/list?access_token=%s' % self.token
        # data = {'dept_id': dept_id, 'cursor': 0, "size": 100}
        ret = requests.get(url)
        res = json.loads(ret.text)
        return res

    def get_dept_id(self, dept_name):
        """
        :param department_name: 部门名称 string
        :return: 部门ID int
        """
        department_list = self.get_all_dept()['department']
        department_id = [department['id'] for department in department_list if department['name'] == dept_name]
        if len(department_id) < 1:
            # raise ValueError("Can`t find department {}".format(department_name))
            print("Can`t find department {}, return 0.".format(dept_name))
            return 0  # 表示无此部门
        else:
            return department_id[0]  # 根据传给的部门名字，返回部门id

    def get_sub_dept(self, department_id):
        """
        :param department_id: 父部门id
        :return: 子部门id list
        """
        url = 'https://oapi.dingtalk.com/department/list_ids?access_token=%s&id=%s' % (self.token, department_id)
        ret = requests.get(url)
        res = json.loads(ret.text)
        return res

    def get_all_users(self):
        user_list = []
        all_dept_id = [dept['id'] for dept in self.get_all_dept()['department']]
        # print(all_dept_id)
        for dept_id in all_dept_id:
            user_list.extend(self.get_dept_user(dept_id)['userlist'])
        return user_list

    def get_all_user_dict(self):
        user_dict = {}
        for user in self.get_all_users():
            user_dict[user['unionid']] = user    # 之前使用userid
        return user_dict

    def gen_dept_dict(self):
        dept_dict = {}
        # 生成一个部门字典，key为部门id，value为部门属性对象
        for i in self.get_all_dept()['department']:
            dept_dict[i["id"]] = i
        # 将上面生成的部门字典，每个value都添加ou字段前缀
        for dept_id, dept in dept_dict.items():
            ou = ''
            while dept['id'] != 1:
                ou = ou + "ou=" + dept['name'] + ","
                dept = dept_dict[dept['parentid']]
            # print(ou)
            # 添加ou属性
            dept_dict[dept_id]['ou'] = ou
        return dept_dict